<template>
  <div class="container pageSetting_container">
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane v-if="showColumn" name="displaySetting" label="显示设置">
        <div class="setting">
          <div class="tips">在表格中显示以下字段</div>
          <div ref="scrollRef" class="tableData changeStylePage">
            <div v-for="(item, index) in newData" :key="index" class="tableRow">
              <div class="table-left">
                <div class="switch">
                  <el-switch
                    v-model="item.isShow"
                    active-color="#13ce66"
                    inactive-color="#999999"
                    @change="changeState"
                  />
                </div>
                <div class="name">{{ item.label }}</div>
                <div class="num">
                  <!--                  <el-input-number-->
                  <!--                    v-model="item.width"-->
                  <!--                    :min="0"-->
                  <!--                    style="height: 30px; width: 120px;"-->
                  <!--                    controls-position="right"-->
                  <!--                    label="描述文字"-->
                  <!--                  />-->

                  <el-popover
                    placement="bottom"
                    width="848"
                    trigger="hover"
                    popper-class="PageConfiguration_chooseWidth"
                  >
                    <div class="num_choose">
                      <el-slider v-model="item.width" :max="800" @change="(val)=>sliderChange(val,index)" />
                    </div>
                    <a slot="reference" class="num_setting">设定宽度</a>
                  </el-popover>
                  <div class="num_show">{{ item.width?item.width:'未设置' }}</div>
                </div>
              </div>
              <div class="line" />
              <div class="table-right">
                <svg-icon icon-class="drag2" />
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="searchField" label="字段搜索">
        <div class="setting">
          <div class="tips">使用以下字段作为搜索以及默认条件</div>
          <div ref="scrollRef2" class="tableData2 changeStyleSearch">
            <div v-for="(item, index) in newData2" :key="index" class="tableRow">
              <div class="table-left">
                <div class="switch">
                  <el-switch
                    v-model="item.isShow"
                    active-color="#13ce66"
                    inactive-color="#999999"
                  />
                </div>
                <div class="name">{{ item.label }}</div>
                <div class="num">
                  <el-select v-if="item.type== 'select'" v-model="item.defaultValue" placeholder="请选择">
                    <el-option
                      v-for="itemChild in item.options"
                      :key="itemChild.value"
                      :label="itemChild.label"
                      :value="itemChild.value"
                    />
                  </el-select>
                  <el-select v-if="item.type== 'dict'" v-model="item.defaultValue" placeholder="请选择">
                    <el-option
                      v-for="itemChild in item.options"
                      :key="itemChild.dictCode"
                      :label="itemChild.dictLabel"
                      :value="itemChild.dictCode"
                    />
                  </el-select>
                  <!--                  <el-select v-if="item.type=== 'select-multiple'" v-model="item.defaultValue" multiple collapse-tags filterable>-->
                  <!--                    <el-option-->
                  <!--                      v-for="itemChild in item.options"-->
                  <!--                      :key="itemChild.value"-->
                  <!--                      :label="itemChild.label"-->
                  <!--                      :value="itemChild.value"-->
                  <!--                    />-->
                  <!--                  </el-select>-->

                  <!--   自定义多选组件    -->
                  <JLINKSelectMultiple
                    v-if="item.type=== 'select-multiple'"
                    v-model="item.defaultValue"
                    :select-options="item.options"
                    placeholder="全部"
                  />

                  <el-input v-else-if="item.type=='input'" v-model="item.defaultValue" placeholder="请输入" />
                  <TimeRangeSearch v-if="item.type==='time'" style="width:180px;background:white;border-radius:5px;" :band-value.sync="item.defaultValue" />
                  <!-- <el-date-picker
                    v-else-if="item.type=='time'"
                    v-model="item.defaultValue"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="yyyy-MM-dd HH时"
                    value-format="yyyy-MM-dd HH:mm"
                    placeholder="请选择"
                  /> -->
                </div>
              </div>
              <div class="line" />
              <div class="table-right">
                <svg-icon icon-class="drag2" />
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="defaultSort" label="默认排序">
        <div class="AddOrUpdate_main add_container column_one">
          <el-form ref="form" class="main_main" :model="pageDatas">
            <el-form-item label="默认排序项">
              <el-select v-model="pageDatas.orderByColumn" placeholder="请选择">
                <el-option
                  v-for="item in defaultSearchColumns"
                  :key="item.prop"
                  :label="item.label"
                  :value="item.prop"
                  :disabled="(item.canOrder===false)?true:false"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="默认排序方式">
              <el-select v-model="pageDatas.isAsc" placeholder="请选择">
                <el-option label="升序" value="asc" />
                <el-option label="降序" value="desc" />
              </el-select>
            </el-form-item>
            <el-form-item label="默认每页显示行数">
              <el-select v-model="pageDatas.pageSize" placeholder="请选择">
                <el-option label="20" value="20" />
                <el-option label="50" value="50" />
                <el-option label="200" value="200" />
                <el-option label="500" value="500" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div class="bottomBtn">
      <div v-if="activeName == 'displaySetting'" class="left-button">
        <div class="openAll" @click.stop="openAllDisplaySwitch">开启所有</div>
        <div @click.stop="closeAllDisplaySwitch">关闭所有</div>
      </div>
      <div v-else-if="activeName == 'searchField'" class="left-button">
        <div class="openAll" @click.stop="openAllFieldSwitch">显示所有</div>
        <div @click.stop="closeAllFieldSwitch">隐藏所有</div>
      </div>
      <div v-else class="left-button" />
      <div class="right-button">
        <el-button @click.stop="backDefault">恢复默认</el-button>
        <el-button type="cancel" @click.stop="cancel">取消</el-button>
        <el-button @click.stop="onSubmit">保存</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { savePageSettings, backDefault } from '@/api/common/common'
import Sortable from 'sortablejs'
export default {
  props: {
    layerid: {},
    settingData: {}
  },
  data() {
    return {
      typeLabel: '页面配置',
      activeName: 'displaySetting',
      TableColumns: [],
      SearchColumns: [],
      defaultSearchColumns: [],
      pageDatas: {
        orderByColumn: '',
        isAsc: '',
        pageSize: ''
      },
      optionData: [],
      settingDatas: {},
      newData: [],
      newData2: [],
      showColumn: true,
      pageNoCreateTimeUpdateTime: ['saleReport', 'purchaseStatistics', 'warehouseReport']
    }
  },
  mounted() {
    if (this.$route.path.indexOf('equipmentReport/') > 0) {
      this.showColumn = false
      this.activeName = 'searchField'
    }
    const tableColumnsCache = JSON.parse(JSON.stringify(this.settingData.TableColumns)) // 解决传值过来无法修改值的bug
    const searchColumnsCache = JSON.parse(JSON.stringify(this.settingData.SearchColumns)) // 解决传值过来无法修改值的bug

    // 2023年11月20日：通过遍历代码里写死的默认的字段，以写死的默认的字段为准，来展示

    const tableColumnsCache_old = JSON.parse(JSON.stringify(this.settingData.defaultTableColumns))
    const searchColumnsCache_old = JSON.parse(JSON.stringify(this.settingData.defaultSearchColumns))

    //  2023年11月20日：新的代码里写死的字段，如果旧的已保存的页面配置里没有，加进去
    tableColumnsCache_old.forEach(item => {
      if (!tableColumnsCache.some(iitem => item.prop == iitem.prop)) {
        tableColumnsCache.push(tableColumnsCache_old.filter(iitem => item.prop == iitem.prop)[0])
      }
    })
    //  2023年11月20日：新的代码里写死的字段，如果旧的已保存的页面配置里没有，加进去
    searchColumnsCache_old.forEach(item => {
      if (!searchColumnsCache.some(iitem => item.prop == iitem.prop)) {
        searchColumnsCache.push(searchColumnsCache_old.filter(iitem => item.prop == iitem.prop)[0])
      }
    })

    const tableColumnsCache_del = JSON.parse(JSON.stringify(tableColumnsCache)) // 深拷贝值来操作
    const searchColumnsCache_del = JSON.parse(JSON.stringify(searchColumnsCache)) // 深拷贝值来操作

    //  2023年11月20日：旧的页面设置里已保存的字段，如果新的代码里已经把这个字段去掉了，那也去掉
    tableColumnsCache_del.forEach(item => {
      if (!tableColumnsCache_old.some(iitem => item.prop == iitem.prop)) {
        tableColumnsCache.splice(tableColumnsCache.findIndex(iitem => item.prop == iitem.prop), 1)
      }
    })
    //  2023年11月20日：旧的页面设置里已保存的字段，如果新的代码里已经把这个字段去掉了，那也去掉
    searchColumnsCache_del.forEach(item => {
      if (!searchColumnsCache_old.some(iitem => item.prop == iitem.prop)) {
        searchColumnsCache.splice(searchColumnsCache.findIndex(iitem => item.prop == iitem.prop), 1)
      }
    })

    tableColumnsCache.forEach(item => {
      if ('isShow' in item === false) {
        item.isShow = true
      }
      // this.$set(item, 'isShow', true)
      if (!item.width) {
        item['width'] = undefined
      }
    })
    this.defaultSearchColumns = this.$deepClone(tableColumnsCache)
    // 如果 tableColumnsCache 里面，没有 createTime 和 updateTime ，手动加上
    const thisPath = this.$route.path
    if (this.pageNoCreateTimeUpdateTime.every(item => thisPath.indexOf(item) == -1)) {
      if (tableColumnsCache.filter(item => item.prop === 'createTime').length === 0) {
        this.defaultSearchColumns.push({
          prop: 'createTime',
          label: '创建时间'
        })
      }
      if (tableColumnsCache.filter(item => item.prop === 'updateTime').length === 0) {
        this.defaultSearchColumns.push({
          prop: 'updateTime',
          label: '更新时间'
        })
      }
    }

    searchColumnsCache.forEach(item => {
      if ('isShow' in item === false) {
        item.isShow = true
      }
      // this.$set(item, 'isShow', true)
      if (!item.defaultValue) {
        item['defaultValue'] = undefined
      }
    })
    this.$set(this.settingDatas, 'TableColumns', tableColumnsCache)
    this.newData = this.$deepClone(tableColumnsCache)
    this.$set(this.settingDatas, 'SearchColumns', searchColumnsCache)
    this.newData2 = this.$deepClone(searchColumnsCache)
    // 获取页面的pageData，根据pageData的字段来修改默认值
    this.newData2.forEach(ele => {
      if (ele.prop in this.$parent.$parent.pageData) {
        ele.defaultValue = this.$parent.$parent.pageData[ele.prop]
      }
    })
    this.pageDatas = JSON.parse(JSON.stringify(this.settingData.pageData))
    this.$nextTick(() => {
      if (this.showColumn) {
        this.rowDrop()
      }

      this.rowDrop2()
    })
  },
  methods: {
    rowDrop() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.tableData')
      const _this = this

      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const cacheData1 = _this.$deepClone(_this.newData[oldIndex])
          const cacheTableData = _this.$deepClone(_this.newData)
          cacheTableData.splice(oldIndex, 1)
          cacheTableData.splice(newIndex, 0, cacheData1)
          _this.newData = []
          const cacheScroll = _this.$refs.scrollRef.scrollTop
          setTimeout(() => { // 加延时重置表格
            _this.newData = cacheTableData
            setTimeout(() => {
              _this.$refs.scrollRef.scrollTop = cacheScroll
            }, 1)
          }, 1)
        }
      })
    },
    rowDrop2() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.tableData2')
      const _this = this

      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const cacheData1 = _this.$deepClone(_this.newData2[oldIndex])
          const cacheTableData = _this.$deepClone(_this.newData2)
          cacheTableData.splice(oldIndex, 1)
          cacheTableData.splice(newIndex, 0, cacheData1)
          _this.newData2 = []
          const cacheScroll = _this.$refs.scrollRef2.scrollTop
          setTimeout(() => { // 加延时重置表格
            _this.newData2 = cacheTableData
            setTimeout(() => {
              _this.$refs.scrollRef2.scrollTop = cacheScroll
            }, 1)
          }, 1)
        }
      })
    },
    changeState() {
    },
    // 开启显示设置所有开关
    openAllDisplaySwitch() {
      this.newData.forEach((ele) => {
        ele.isShow = true
      })
    },
    // 关闭显示设置所有开关
    closeAllDisplaySwitch() {
      this.newData.forEach((ele) => {
        ele.isShow = false
      })
    },
    // 开启显示设置所有开关
    openAllFieldSwitch() {
      this.newData2.forEach((ele) => {
        ele.isShow = true
      })
    },
    // 关闭显示设置所有开关
    closeAllFieldSwitch() {
      this.newData2.forEach((ele) => {
        ele.isShow = false
      })
    },
    cancel() {
      this.$layer.close(this.layerid) // 关闭弹框
    },
    // 提交
    onSubmit() {
      if (this.showColumn && (this.newData.filter(item => item.isShow).length === 0)) {
        this.$message.warning('请至少保留一项显示字段')
        return
      }
      if (this.newData2.filter(item => item.isShow).length === 0) {
        this.$message.warning('请至少保留一项查询字段')
        return
      }
      console.log(this.newData)
      console.log(this.newData2)
      const submitData = {}
      // if (this.newData && this.newData.length > 0) {
      this.settingDatas.TableColumns = this.$deepClone(this.newData)
      // }
      // if (this.newData2 && this.newData2.length > 0) {
      this.settingDatas.SearchColumns = this.$deepClone(this.newData2)
      // }
      if (this.settingDatas.TableColumns.some(e => e.width < 0) || this.settingDatas.TableColumns.some(e => e.width < 0)) {
        this.$message.warning('宽度不能为负数')
        return false
      }
      this.settingDatas.pageData = this.pageDatas
      submitData.userId = this.settingData.userId
      submitData.pageId = this.settingData.pageId
      if (this.settingData.id) {
        submitData.id = this.settingData.id
      }
      submitData.json = JSON.stringify(this.settingDatas)
      savePageSettings(submitData).then(res => {
        this.$message({
          message: res.msg,
          type: 'success'
        })
        // this.$layer.close(this.layerid) // 关闭弹框
        // this.$parent.getPageSettings() // 调用父组件的方法

        location.reload() // 直接刷新页面吧
      })
    },
    backDefault() {
      backDefault({ userId: this.settingData.userId, pageId: this.settingData.pageId }).then(res => {
        this.$message({
          message: res.msg,
          type: 'success'
        })
        // this.$layer.close(this.layerid) // 关闭弹框
        // this.$parent.getPageSettings() // 调用父组件的方法

        location.reload() // 直接刷新页面吧
      })
    },
    sliderChange(val, index) {
      if (val !== 0 && val < 100) {
        this.newData[index].width = 100
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-select__tags{
   max-width: 142.5px !important;
}
/deep/ .el-input-number.is-controls-right span {
  display: inline-block;
  height: 15px;
  width: 24px;
  line-height: 15px;
}
/deep/ .el-input-number .el-input {
  margin-top: -2px;
}
/deep/ .el-input--medium .el-input__inner {
  height: 30px !important;
  line-height: 30px;
  padding-left: 10px;
}
/deep/ .el-input-number--medium{
  line-height: 35px;
}
.changeStylePage{
  overflow-y: auto;
  flex: 1;
}

.changeStylePage /deep/ .el-input-number.is-controls-right .el-input__inner{
  padding-right: 34px;
  width: 120px;
}
.changeStyleSearch{
  overflow-y: auto;
  height: 100%;
}
.changeStyleSearch /deep/ .el-input {
    width: 180px;
}
/deep/ .svg-icon {
  height: 20px;
  width: 22px;
}
/deep/ .el-form-item__label {
  font-size: 14px !important;

  font-weight: 400;
  color: #666666;
  width: 180px;
}
.num{
.el-input,.el-select, .el-date-editor.el-input{
  width: 180px !important;
}
/deep/ .el-input__suffix{
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

}
.changeStylePage /deep/ .el-input{
  width: 220px;
 }
.container {
  width: 100%;
  overflow: hidden;
  .setting {
    //height: 650px;
    width: 100%;
    padding: 25px 20px 0 20px;
    //overflow-y: auto;
    height: 100%;
    display: flex;flex-direction: column;
    .tips {
      margin-bottom: 21px;
      font-size: 14px;

      font-weight: 400;
      color: #666666;
    }
    .tableRow {
      width: 100%;
      display: flex;
      flex-direction: row;
      align-items: center;
      &:nth-child(even) {
        background: #F7FAFF;
      }
      &:nth-child(odd) {
        background: #EBF2FF;
      }
      .table-left {
        height: 40px;
        width: 539px;
        border-right: 1px solid #efefef;
        // margin-right: 1px;
        // padding: 5px 0;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        .switch {
          margin: 0 24px;
        }
        .name {
          text-align: center;
          font-size: 14px;

          font-weight: 400;
          color: #333333;
        }
        .num {
          width: 180px;
          font-size: 14px;
          display: flex;
          .num_setting{
            padding-right: 20px;
            color: #387bfc;
          }
          .num_show{
            color: #c0c4cc;
          }
        }
      }
      //   .line{
      //       height: 40px;
      //       width: 1px;
      //   }
      .table-right {
        height: 40px;
        width: 80px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
      }
    }
  }
  .bottomBtn {
    padding: 20px;
    height: 70px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    .left-button {
      font-size: 14px;

      font-weight: 400;
      color: #666666;
      display: flex;
      flex-direction: row;
      align-items: center;
      div {
        cursor: pointer;
      }
      .openAll {
        margin-right: 20px;
      }
    }
  }
}
.el-tab-pane{
  justify-content: center;
}
.container /deep/ .el-input{
  padding-right: 0px;
}
.el-tabs{
  height: calc(100% - 70px);
}
.column_one{
  /deep/ .el-form-item{
    width: calc(100% - 40px);
    .el-form-item__label{
      width: 140px;
    }
  }
}
/deep/ .el-date-editor{
  height: 30px;
}
</style>
